<template>
  <div class="flex gap2">
    <ElSelect v-model="seedName" placeholder="模块" :disabled="props.disabled">
      <ElOption v-for="(seed, seedName) in seedOptions" :label="seed.label" :value="seedName" :key="seedName" />
    </ElSelect>
    <ElSelect v-model="selfColumn" placeholder="当前列" :disabled="props.disabled">
      <ElOption v-for="(column, columnName) in columnOptions" :label="column.label" :value="columnName" :key="columnName" />
    </ElSelect>
    <ElSelect v-model="targetColumn" placeholder="目标列" :disabled="props.disabled">
      <ElOption v-for="(column, columnName) in columnOptions" :label="column.label" :value="columnName" :key="columnName" />
    </ElSelect>
  </div>
</template>
<script setup lang="ts">
  import { ElOption, ElSelect } from 'element-plus';
  import { computed, ref, watch } from 'vue';
  import { getSeeds, getSeed } from '@/views/seed-dev';
  import { SeedConfiguration } from '@/views/dev-types';
import { getRefColumns } from '../../utils/SeedUtil';

  const props = defineProps<{seedName?: string, selfColumn?: string, targetColumn?: string, disabled?: boolean}>()
  const emits = defineEmits(['update:seedName', 'update:selfColumn', 'update:targetColumn'])

  const seedName = ref<string>(props.seedName)
  const selfColumn = ref<string>(props.selfColumn)
  const targetColumn = ref<string>(props.targetColumn)

  const seedOptions = computed(() => {
    const ret: Record<string, SeedConfiguration> = {}
    const seeds = getSeeds()
    for(const seedName in seeds) {
      const seed = seeds[seedName]
      const refColumns = getRefColumns(seed)
      if(Object.keys(refColumns).length > 1) ret[seedName] = seed
    }

    return ret
  })
  const columnOptions = computed(() => {
    if(!seedName.value) return {}

    const seed = getSeed(seedName.value)
    return getRefColumns(seed)
  })

  watch(() => props.seedName, (val) => seedName.value = val)
  watch(() => props.selfColumn, (val) => selfColumn.value = val)
  watch(() => props.targetColumn, (val) => targetColumn.value = val)

  watch(seedName, (val) => {
    emits('update:seedName', val)
    selfColumn.value = void 0
    targetColumn.value = void 0
  })
  watch(selfColumn, (val) => emits('update:selfColumn', val))
  watch(targetColumn, (val) => emits('update:targetColumn', val))
</script>